package indigo.captcha;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;

import com.octo.captcha.service.image.ImageCaptchaService;

public class ImageCaptchaController {
	private static final Logger logger = LoggerFactory.getLogger(ImageCaptchaController.class);

	private final ImageCaptchaService imageCaptchaService;

	public ImageCaptchaController(ImageCaptchaService imageCaptchaService) {
		this.imageCaptchaService = imageCaptchaService;
	}

	@RequestMapping(produces = MediaType.IMAGE_JPEG_VALUE)
	public ResponseEntity<byte[]> captchaImage(WebRequest request) throws IOException {
		Object challenge = imageCaptchaService.getChallengeForID(request.getSessionId());
		if (challenge instanceof BufferedImage) {
			ByteArrayOutputStream bytes = new ByteArrayOutputStream();
			ImageIO.write((BufferedImage) challenge, "jpg", bytes);

			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.IMAGE_JPEG);
			headers.setCacheControl("no-cache,no-store,must-revalidate");
			headers.setPragma("no-cache");
			headers.setExpires(0);

			return new ResponseEntity<>(bytes.toByteArray(), headers, HttpStatus.OK);
		} else {
			if (logger.isWarnEnabled()) {
				logger.warn("Non-image captcha challenge detected while requesting image captcha");
			}
			return new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE);
		}
	}
}